package com.seele.tigerwallet.model;

import android.text.TextUtils;
import android.util.Log;

import com.seele.base.utils.FileIOUtils;
import com.seele.base.utils.FileUtils;
import com.seele.base.utils.LogUtils;
import com.seele.base.utils.SDCardUtils;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.api.APIObjectCallBack;
import com.seele.tigerwallet.ui.application.SeeleApplication;
import com.seele.tigerwallet.ui.constants.Constant;
import com.seele.tigerwallet.ui.utils.GsonUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.utils.Utils;
import com.seele.tigerwallet.wallet.WalletManager;

import org.w3c.dom.Text;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfo implements Serializable {


    private static Object mLock = new Object();
    public int count = 0;

    private String url3 = "/wallet/v1/quotation/icon/";

    public String getUrl(String id) {

        return getPic() + id + ".png";
    }


    public String getTokeninfoURL(String id) {

        return "http://" + id + ".png";
    }




    private String getPic() {
        return "https://" + pichost + url3;
    }


    public static String getApiUrl(String url) {
        if (!TextUtils.isEmpty(url)) {
            return "https://" + url + "/wallet/";
        }
        return null;

    }

    public interface OnUserInfoListener {
        void onResponse(UserInfo userInfo);

        void onResponseError(Throwable throwable);

        void onFailureError(Call call, Throwable t);
    }


    private static UserInfo ourInstance = null;


    public static UserInfo get() {
        synchronized (mLock) {
            if (ourInstance == null) {
                ourInstance = new UserInfo();
            }
            return ourInstance;
        }
    }


    private UserInfo() {
    }


    public String session;
    public String token;

    public String loginhost;//登录地址

    public List<String> hostList;//所有的登录地址

    public String fronthost;//业务地址

    public String pichost;//图片地址

    public String filehost;//文件地址

    public String exchangerate;//汇率

    public int company;//货币单位

    public int language;//语言选择

    public String address;//当前用户钱包地址

    public String uuid; //当前APP UUID

    public String name; //当前钱包名字

    public String getAddress() {
        if (TextUtils.isEmpty(address)) {
            return " ";
        }
        return address;
    }

    public String getSession() {


        return session;
    }

    public void setSession(String session) {
        this.session = session;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getFronthost() {
        return fronthost;
    }

    public void setFronthost(String fronthost) {
        this.fronthost = fronthost;
    }

    public String getPichost() {
        return pichost;
    }

    public void setPichost(String pichost) {
        this.pichost = pichost;
    }

    public String getFilehost() {
        return filehost;
    }

    public void setFilehost(String filehost) {
        this.filehost = filehost;
    }

    public String getExchangerate() {
        if (TextUtils.isEmpty(exchangerate)) {
            //检查网络状况  重新获取汇率

            return "0.00";
        }
        return exchangerate;
    }

    public void savaUserInfo(UserInfo userInfo) {
        SPUtils.saveUserInfo(userInfo);

    }

    public UserInfo getUserInfo() {
        UserInfo userInfo = SPUtils.getUserInfo(UserInfo.get());
        ourInstance = userInfo;
        return ourInstance;

    }


    /**
     * 数据组装
     *
     * @param walletInfoModel
     */
    private UserInfo handlerData(WalletInfoModel walletInfoModel) {
        UserInfo userInfo = UserInfo.get();
        if (!TextUtils.isEmpty(walletInfoModel.session)) {
            Log.e("handlerData",":session::"+walletInfoModel.session);
            userInfo.session = walletInfoModel.session;
        }

        if (!TextUtils.isEmpty(walletInfoModel.token)) {
            userInfo.token = walletInfoModel.token;
        }

        if (null != walletInfoModel.filehost && walletInfoModel.filehost.size() > 0) {
            userInfo.filehost = walletInfoModel.filehost.get(0);
        }
        if (null != walletInfoModel.fronthost && walletInfoModel.fronthost.size() > 0) {
            userInfo.fronthost = walletInfoModel.fronthost.get(0);
        }
        if (null != walletInfoModel.pichost && walletInfoModel.pichost.size() > 0) {
            userInfo.pichost = walletInfoModel.pichost.get(0);
        }

        return userInfo;
    }

    /**
     * 登录
     *
     * @param listener
     */
    public void login(final OnUserInfoListener listener) {

        String jPushRegistrationID = Utils.getJPushId();
        Log.i("jpush", "jPushRegistrationID:" + jPushRegistrationID);
        APIModule.getApi()
                .login(uuid, jPushRegistrationID, 1)
                .enqueue(new APIObjectCallBack<WalletInfoModel>() {

                    @Override
                    protected void onResponse(WalletInfoModel response) {
                        try {
                            if (null != response) {
                                UserInfo userInfo = handlerData(response);
                                APIModule.setSession(userInfo.session);
                                savaUserInfo(userInfo);
                                if (null != listener) {
                                    listener.onResponse(userInfo);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        if (null != listener) {
                            listener.onResponseError(e);
                        }

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        if (null != listener) {
                            listener.onFailureError(call, t);
                        }
                    }

                });

    }


    public String getNewSession() {
        APIModule.setFlag(false);
        String session = null;
        uuid = getUuid();
        if (TextUtils.isEmpty(uuid)) {
            return null;
        }
        String jPushRegistrationID = Utils.getJPushId();
        try {
            Response<String> response = APIModule.getApi().login(uuid, jPushRegistrationID, 1).execute();
            if (response.isSuccessful()) {
                String string = response.body();
                if (!TextUtils.isEmpty(string)) {
                    Log.i("jpush", "walletInfoModel:" + string);
                    if (null != response) {
                        BaseModel baseModel = GsonUtil.parseJsonWithGson(string, BaseModel.class);
                        UserInfo userInfo = handlerData(baseModel.data);
                        session = userInfo.session;
                        APIModule.setSession2(userInfo.session);
                        savaUserInfo(userInfo);

                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return session;

    }


    /**
     * 获取本地的UUID
     *
     * @return
     */
    public String getUuid() {
        if (TextUtils.isEmpty(uuid)) {
            uuid = getUuidByFile();
        }

        return uuid;
    }

    public boolean setUuid(String uuid) {
        this.uuid = uuid;
        return saveUuidToFile(uuid);

    }


    /**
     * 获取文件中的 UUid
     *
     * @return
     */
    private String getUuidByFile() {
        String uuid = null;
        if (SDCardUtils.isSDCardEnableByEnvironment()) {
            String path = SDCardUtils.getSDCardPathByEnvironment();
            File file = new File(path + Constant.File.FILE_CONFIG);
            if (FileUtils.isFileExists(file)) {
                uuid = FileIOUtils.readFile2String(file);
            }
        }
        LogUtils.dTag("uuid", "用户ID:" + uuid);
        return uuid;

    }


    /**
     * 获取文件中的 UUid
     *
     * @return
     */
    private boolean saveUuidToFile(String uuid) {
        boolean isExists = false;
        if (!TextUtils.isEmpty(uuid)) {
            if (SDCardUtils.isSDCardEnableByEnvironment()) {
                String path = SDCardUtils.getSDCardPathByEnvironment();
                File file = new File(path + Constant.File.FILE_CONFIG);
                isExists = FileUtils.createFileByDeleteOldFile(file);
                if (isExists) {
                    isExists = FileIOUtils.writeFileFromString(file, uuid);
                }
            }

        }
        return isExists;

    }

}













